<template>
	<view>
		<navbar title="个人网盘" left="">
			<view>
				<view style="display: flex;align-items: center;">
					<view @click="goPage('download')">
						<u-icon name="download" color="#373737" size="30" style="margin-right: 3px;"></u-icon>
					</view>
				</view>
			</view>
		</navbar>
		<u-search v-model="search" :showAction="false" placeholder="请输入文件名称或关键词" @blur="sousuo"></u-search>
		<view>
			<u-tabs :list="tabs" @click="ctabs" lineWidth="30" style="background-color: white;"></u-tabs>
			<!-- 路径 -->
			<uni-breadcrumb separator="/" style="background-color: #f5f5f5;padding: 5px;">
				<uni-breadcrumb-item v-for="(item,index) in path" :key="index">
					<view @click="back(item.to,index)">
						{{item.name}}
					</view>
				</uni-breadcrumb-item>
			</uni-breadcrumb>
		</view>
		<!-- 到顶部 -->
		<u-back-top :scroll-top="scrollTop"></u-back-top>
		<!-- 文件列表 -->
		<scroll-view @scrolltoupper="toupper" scroll-y="true" @scrolltolower="tolower" class="file-list">
			<unicloud-db @load="loadlist" loadtime="manual" ref="udb"
				v-slot:default="{data, pagination, loading, hasMore}" collection="item" :orderby="orderby"
				:field="field" :where="itemwhere">
				<view v-if="hasMore||data.length>0" v-for="(item,index) in data" :key="item._id"
					@click="listclick(item,index)">
					<u-transition :show="true">
						<item_file v-if="item.type=='file'" :item="item">
							<view style="width: 30px;" @click.stop="setinfo(item,index)">
								<u-icon name="more-dot-fill" size="30"></u-icon>
							</view>
						</item_file>
						<item_img v-if="item.type=='img'" :item="item">
							<view style="width: 30px;" @click.stop="setinfo(item,index)">
								<u-icon name="more-dot-fill" size="30"></u-icon>
							</view>
						</item_img>
						<item_doc v-if="item.type=='document'" :item="item">
							<view style="width: 30px;" @click.stop="setinfo(item,index)">
								<u-icon name="more-dot-fill" size="30"></u-icon>
							</view>
						</item_doc>
						<item_apk v-if="item.type=='apk'||item.type=='ipa'" :item="item">
							<view style="width: 30px;" @click.stop="setinfo(item,index)">
								<u-icon name="more-dot-fill" size="30"></u-icon>
							</view>
						</item_apk>
						<item_video v-if="item.type=='video'" :item="item">
							<view style="width: 30px;" @click.stop="setinfo(item,index)">
								<u-icon name="more-dot-fill" size="30"></u-icon>
							</view>
						</item_video>
						<item_other v-if="item.type=='other'" :item="item">
							<view style="width: 30px;" @click.stop="setinfo(item,index)">
								<u-icon name="more-dot-fill" size="30"></u-icon>
							</view>
						</item_other>
					</u-transition>
				</view>
				<u-loadmore v-if="loading" loadingText="拼命加载中" status="loading" />
				<view v-if="data.length==0&&!loading&&!hasMore" style="text-align: center;margin-top: 20px;">
					<u-empty mode="data" text="还没有文件呢~">
					</u-empty>
				</view>
			</unicloud-db>
		</scroll-view>
		<!-- 二维码 -->
		<u-popup round="5" @close="qrshow=false" :show="qrshow" mode="center" closeOnClickOverlay>
			<view style="padding: 10px;" @click="save">
				<uqrcode ref="uqrcode" canvas-id="qrcode" :value="link"
					:options="{ margin: 10 ,foregroundImageSrc:'https://mp-e8736984-eb69-4fda-8fbc-8b94a79af7f9.cdn.bspapp.com/icon/logo.png'}">
				</uqrcode>
				<p class="save-qrcode">点击保存</p>
			</view>
		</u-popup>
		<!-- 重命名 -->
		<u-modal closeOnClickOverlay @cancel="setnameshow=false" @confirm="setname" showCancelButton :show="setnameshow"
			title="重命名">
			<u--input placeholder="请输入新名称" border="surround" v-model="rename" style="margin-top: 10px;"></u--input>
		</u-modal>
		<u-popup :round="10" :show="fbsqshow" @close="fbsqshow=false">
			<view class="release-community">
				<h3>发布社区</h3>
				<u-form>
					<u-form-item label="购买价格(单位RMB)" labelPosition="top" labelWidth="200">
						<u--input placeholder="请输入价格" border="surround" v-model="item_temp.money"
							style="margin-top: 10px;"></u--input>
					</u-form-item>
					<view class="classify" @click="classifyShow=true">
						<p>选择分类</p>
						<p>{{classifyTemp}}</p>
					</view>
					<u-button style="margin-top: 10px;" text="发布" type="primary" @click="passitem"></u-button>
					<u-button text="撤回" @click="qxpassitem" style="margin-top: 10px;"></u-button>
				</u-form>
			</view>
		</u-popup>
		<u-picker :closeOnClickOverlay="true" @close="classifyShow=false" :show="classifyShow" ref="uPicker"
			:columns="columns" @confirm="confirmClassify" @change="changeHandler"></u-picker>
		<u-popup :round="10" :show="contentshow" @close="contentshow=false">
			<view class="file-info">
				<h3>文件介绍</h3>
				<u--textarea style="margin-top: 10px;" v-model="item_temp.content" placeholder="请输入文件介绍"></u--textarea>
				<u-button text="保存" type="primary" @click="setcontent" style="margin-top: 10px;"></u-button>
			</view>
		</u-popup>
		<!-- 文件操作 -->
		<u-popup :round="10" :show="setshow" @close="setshow=false">
			<view class="file-operate">
				<view style="display: flex;align-items: center;">
					<image v-if="item_temp.iconError!='error'" @error="imageError"
						style="border-radius: 5px;max-width: 53.89221px;height: 45px;"
						:src="geticon(item_temp.type,item_temp.icon)" mode="heightFix"></image>
					<u--image v-else radius="5" mode="scaleToFill" src="null" width="45px" height="45px"></u--image>
					<view style="margin-left: 10px;">
						<u--text lines="1" :text="item_temp.title" size="16"></u--text>
						<p style="color: #909399;font-size: 13px;">{{item_temp.time}} {{item_temp.sizes}}</p>
					</view>
				</view>
				<u-divider style="margin-top: 10px;"></u-divider>
				<u-alert @click="copy('http://x2.ink/pages/share/share?id='+item_temp._id,'复制成功')"
					:description="'http://x2.ink/pages/share/share?id='+item_temp._id" title="长链接:"
					type="primary"></u-alert>
				<u-alert @click="copy(link,'复制成功')" title="短链接:" :description="link" type="info"
					style="margin-top: 10px;"></u-alert>
				<u-divider text="其他操作"></u-divider>
				<u-grid col="4" style="margin: 10px 0;">
					<u-grid-item v-if="item_temp.type!='file'" @click="()=>{setshow=false;setnameshow=true}">
						<view>
							<u-icon name="edit-pen" size="35" color="#606266"></u-icon>
							<p>重命名</p>
						</view>
					</u-grid-item>
					<u-grid-item
						v-if="item_temp.type=='img'||item_temp.type=='video'||item_temp.type=='bt'||item_temp.type=='other'"
						@click="()=>{contentshow=true;setshow=false}">
						<view>
							<u-icon name="file-text" size="35" color="#606266"></u-icon>
							<p>修改介绍</p>
						</view>
					</u-grid-item>
					<u-grid-item v-if="item_temp.type=='file'" @click="setfileinfo">
						<view>
							<u-icon name="edit-pen" size="35" color="#606266"></u-icon>
							<p>修改资料</p>
						</view>
					</u-grid-item>
					<u-grid-item v-if="item_temp.url!=null" @click="copy(item_temp.url)">
						<view>
							<u-icon name="attach" size="35" color="#606266"></u-icon>
							<p>文件直链</p>
						</view>
					</u-grid-item>
					<u-grid-item @click="()=>{setshow=false;qrshow=true}">
						<view>
							<u-icon name="/static/qrcode.png" size="35" color="#606266"></u-icon>
							<p>二维码</p>
						</view>
					</u-grid-item>
					<u-grid-item @click="()=>{goPage('movefile','?id='+item_temp._id+'&user_id='+user_id)}">
						<view>
							<u-icon name="rewind-right" size="35" color="#606266"></u-icon>
							<p>移动文件</p>
						</view>
					</u-grid-item>
					<u-grid-item @click="topitem()" v-if="item_temp.top==0">
						<view>
							<u-icon name="arrow-upward" size="35" color="#606266"></u-icon>
							<p>置顶推荐</p>
						</view>
					</u-grid-item>
					<u-grid-item @click="downitem()" v-if="item_temp.top==1">
						<view>
							<u-icon name="arrow-downward" size="35" color="#606266"></u-icon>
							<p>取消置顶</p>
						</view>
					</u-grid-item>
					<u-grid-item @click="download(item_temp.url)" v-if="item_temp.url!=null&&item_temp.type!='img'"
						style="margin-top: 5px;">
						<view>
							<u-icon name="download" size="35" color="#606266"></u-icon>
							<p>本地下载</p>
						</view>
					</u-grid-item>
					<u-grid-item @click="shareapp(item_temp)">
						<view>
							<u-icon name="share-square" size="35" color="#606266"></u-icon>
							<p>分享好友</p>
						</view>
					</u-grid-item>
					<!-- <u-grid-item @click="()=>{setshow=false;fbsqshow=true}">
						<view>
							<u-icon name="home" size="35" color="#606266"></u-icon>
							<p>发布社区</p>
						</view>
					</u-grid-item> -->
					<u-grid-item @click="dele()">
						<view>
							<u-icon name="trash" size="35" color="#606266"></u-icon>
							<p>删除文件</p>
						</view>
					</u-grid-item>
				</u-grid>
			</view>
		</u-popup>
		<!-- 创建合集 -->
		<u-popup round="10" bgColor="#fff" :show="addfileshow" @close="addfileshow=false" mode="center">
			<view class="create-files">
				<h3>{{fileinfo.title}}</h3>
				<u--input style="margin-top: 10px;" placeholder="请输入文件夹标题" border="surround"
					v-model="addset.title"></u--input>
				<u--textarea style="margin-top: 10px;" v-model="addset.content" placeholder="请输入文件夹介绍"></u--textarea>
				<view class="password">
					<p>
						<uni-icons type="locked-filled" size="20" color="#85bcff" /><span>启用访问密码</span>
					</p>
					<u-switch v-model="addset.password_mode" @change="setswitch"></u-switch>
				</view>
				<u--input v-if="addset.password_mode" style="margin-top: 10px;" placeholder="请输入文件夹密码" border="surround"
					v-model="addset.password"></u--input>
				<u-button style="margin-top: 10px;" type="primary" :text="fileinfo.button" @click="filebtn"></u-button>
			</view>
		</u-popup>
		<!-- apk类型选择 -->
		<u-popup :round="10" :show="apkshow" @close="apkshow=false">
			<view class="apk-type">
				<h3>选择方式</h3>
				<view class="type">
					<view @click="goPage('applist','?up='+up)">
						<image src="/static/other/android.png" style="width: 60px;height: 60px;" />
						<p>本机应用</p>
					</view>
					<view @click="selectApkLink" v-if="client!='web'">
						<image src="/static/other/_link.png" style="width: 60px;height: 60px;" />
						<p>自定义</p>
					</view>
					<view @click="selectapk">
						<image src="/static/other/folder-open.png" style="width: 60px;height: 60px;" />
						<p>文件管理</p>
					</view>
				</view>
			</view>
		</u-popup>
		<!-- 上传按钮 -->
		<uni-fab ref="fab" direction="vertical" horizontal="right" @fabClick="upshow=!upshow" />
		<!-- 文件上传 -->
		<u-popup :round="10" :show="upshow" @open="progressShow=false" @close="upshow=false">
			<view class="upload-file">
				<h3>上传文件</h3>
				<view class="tip">
					禁止上传刷单，兼职，网贷，金融，裸聊诈骗，赌博，色情等内容。违者永久封号！
				</view>
				<u-grid col="4" style="margin-top: 10px;">
					<u-grid-item @click="fabclick(index)" v-for="(item,index) in menu_list" style="padding: 5px;">
						<view style="text-align: center;">
							<image :src="item.icon" style="width: 40px;height: 40px;" />
							<p style="font-size: 14px;">{{item.title}}</p>
						</view>
					</u-grid-item>
				</u-grid>
			</view>
		</u-popup>
		<!-- 自定义链接 -->
		<u-popup :round="10" :show="linkshow" @close="linkshow=false">
			<view class="upload-file">
				<h3>自定义链接</h3>
				<view>
					<view class="info">
						<u--image :src="apktemp.icon" width="60" height="60" radius="5">
						</u--image>
						<view style="margin-left: 5px;">
							<u--text size="17" :text="apktemp.title" lines="1"></u--text>
							<view
								style="display: flex;align-items: center;color: #909399;font-size: 12px;margin: 2px 0;">
								<u-rate readonly value="5" size="15"></u-rate>
								<p>5.0</p>
							</view>
							<view style="font-size: 12px;display: flex;align-items: center;color: #909399;">
								<u-icon name="file-text" size="20" color="#909399"></u-icon>
								<p>{{gsbytes(apktemp.size)}}</p>
							</view>
						</view>
						<image class="down" src="../../static/down.png" mode="heightFix"></image>
					</view>
				</view>
				<u--input placeholder="请输入文件下载地址" border="surround" v-model="apktemp.url"
					style="margin: 10px 0;"></u--input>
				<u-button text="上传" type="primary" @click="uploadApkLink"></u-button>
			</view>
		</u-popup>
		<!-- 上传进度条 -->
		<UploadProgress :loading="progressLoading" ref="UploadProgress" :show="progressShow" @close="closeProgress()"
			:list="progresslist">
		</UploadProgress>
	</view>
</template>

<script>
	import store from '@/store/index.js';
	const db = uniCloud.database();
	const dbCmd = db.command
	import ase from '@/common/ar-aes/ar-aes.js'
	export default {
		onReady() {
			this.init()
			this.getClassifyList()
		},
		onPullDownRefresh() {
			if (this.tabcurrent == null) {
				this.itemwhere = `user_id==$cloudEnv_uid&&up=='${this.up}'`
			} else {
				this.itemwhere = `user_id==$cloudEnv_uid&&up=='${this.up}'&&weight=='${this.tabcurrent}'`
			}
			this.$refs.udb.loadData({
				clear: true
			}, (res) => {
				uni.stopPullDownRefresh()
			})
		},
		watch: {
			progresslist(val) {
				if (val.length > 0) {
					this.progressShow = true
				}
			},
			up(val) {
				this.up = val
				this.itemwhere = `user_id==$cloudEnv_uid&&up=='${val}'`
				this.$nextTick(() => {
					this.$refs.udb.loadData({
						clear: true
					})
				})
			}
		},
		onPageScroll(e) {
			this.scrollTop = e.scrollTop;
		},
		data() {
			return {
				progressShow: false,
				progressLoading: false,
				orderby: "top desc,last_time desc,time desc, weight asc",
				field: "password_mode,otherlink,down,ip,time,title,type,up,password,url,weight,last_time,top,duration,size,icon,money,pass",
				classifyTemp: "未选择",
				classifyShow: false,
				columnData: [],
				columns: [],
				linkshow: false,
				contentshow: false,
				tabcurrent: null,
				rename: '',
				apkshow: false,
				addfileshow: false,
				addset: {
					title: null,
					content: "",
					password_mode: false,
					password: null,
					type: 'file'
				},
				qrshow: false,
				setnameshow: false,
				setshow: false,
				scrollTop: 0,
				itemwhere: `user_id==$cloudEnv_uid&&up=='/'`,
				up: "/",
				path: [{
					name: "主页",
					to: "/"
				}],
				menu_list: [{
					title: "集合",
					icon: "../../static/filetype/morenwenjianjia.png"
				}, {
					title: "安装包",
					icon: "../../static/filetype/apk.png"
				}, {
					title: "图片",
					icon: "../../static/filetype/tupian-jpg_png.png"
				}, {
					title: "文档",
					icon: "../../static/filetype/wendang-docx_doc.png"
				}, {
					title: "其他",
					icon: "../../static/filetype/qita.png"
				}],
				fbsqshow: false,
				lanzoulink: null,
				upshow: false,
				search: null,
				tabs: [{
					name: '全部',
					weight: null
				}, {
					name: '文件夹',
					weight: 1
				}, {
					name: '安装包',
					weight: 2
				}, {
					name: '图片',
					weight: 5
				}, {
					name: '文档',
					weight: 6
				}, {
					name: '其他',
					weight: 3
				}],
				item_temp: {},
				index_temp: null,
				link: null,
				fileinfo: {
					title: null,
					button: null
				},
				progresslist: [],
				apktemp: {},
				othersuffix: ['.zip', '.rar', '.txt', '.flac', '.mp3', '.docx', '.pptx', '.xlsx', '.pdf',
					'.psd',
					'.jar', '.7z', '.exe', '.lua', 'doc'
				]
			};
		},
		onShow() {
			this.setshow = false
			this.getUserInfo()
			var that = this
			uni.$off()
			uni.$once("updateFile", async (res) => {
				const itemData = await db.collection("item").where({
					_id: res
				}).field(this.field).get({
					getOne: true
				})
				this.$refs.udb.dataList.find((item, index) => {
					if (item._id === res) {
						this.$set(this.$refs.udb.dataList, index, itemData.result.data);
						return true;
					}
					return false
				})
			})
			uni.$once("moveFile", (res) => {
				const index = this.$refs.udb.dataList.findIndex(item => item._id === res)
				this.$refs.udb.dataList.splice(index, 1);
			})
			uni.$once("addFile", async (res) => {
				if (typeof(res) == 'string') {
					this.newAddFile(res)
				} else {
					res.map(item => {
						this.newAddFile(item)
					})
				}
			})
		},
		methods: {
			toupper() {
				console.log("滚动到顶部了");
			},
			tolower() {
				this.$refs.udb.loadMore()
			},
			async newAddFile(id) {
				if (this.$refs.udb.dataList.find(item => item._id === id)) {
					return
				}
				const itemData = await db.collection("item")
					.where({
						_id: id
					}).field(this.field).get({
						getOne: true
					})
				this.$refs.udb.dataList.unshift(itemData.result.data);
			},
			imageError(e) {
				this.item_temp.iconError = 'error'
				console.log("图片加载失败", e);
			},
			closeProgress() {
				this.progressShow = false
				this.progresslist = []
			},
			init() {
				this.itemwhere = `user_id==$cloudEnv_uid&&up=='${this.up}'`
				this.$refs.udb.loadData({
					clear: true
				}, (res) => {
					this.$refs.udb.loadData({
						clear: true
					})
				})
			},
			download(url) {
				uni.showLoading({
					title: "地址解析中"
				})
				this.getUrl(url, (res) => {
					uni.hideLoading()
					if (res.data.code == 200) {
						let url = res.data.downUrl
						let suffix = res.data.name.substring(res.data.name.lastIndexOf('.') + 1)
						store.commit('setDownload', {
							name: `${this.item_temp.title}.${suffix}`,
							icon: this.geticon(this.item_temp.type, this.item_temp.icon),
							url: url,
							id: this.item_temp._id
						})
						this.goPage('download')
					} else {
						this.openUrl(url)
					}
				})
			},
			async confirmClassify(e) {
				db.collection("item_classify").where({
					name: e.value[1]
				}).get({
					getOne: true
				}).then(res => {
					this.classifyTemp = e.value[1]
					this.item_temp.classify_id = res.result.data.id
					this.classifyShow = false
				})
			},
			changeHandler(e) {
				const {
					columnIndex,
					index
				} = e
				if (columnIndex === 0) {
					this.$refs.uPicker.setColumnValues(1, this.columnData[e.index])
				}
			},
			async getClassifyList() {
				var columns = []
				var columnData = []
				var first = []
				const res = await db.collection("item_classify").get()
				for (var i in res.result.data) {
					if (!first.includes(res.result.data[i].type)) {
						first.push(res.result.data[i].type)
					}
				}
				for (var i in first) {
					columnData[i] = []
					for (var k in res.result.data) {
						if (first[i] == res.result.data[k].type) {
							columnData[i].push(res.result.data[k].name)
						}
					}
				}
				columns[0] = first
				columns[1] = columnData[0]
				this.columnData = columnData
				this.columns = columns
			},
			async setcontent() {
				const res = await db.collection('item').where(`_id=='${this.item_temp._id}'`).update({
					content: this.item_temp.content
				})
				this.message('修改成功')
				this.contentshow = false
			},
			selectApkLink() {
				const plugin = uni.requireNativePlugin('GuoWei-SelectFileModule')
				plugin.chooseFile({
					count: 1,
					extension: ['apk', 'ipa']
				}, res => {
					if (res.code == 1) {
						return
					}
					uni.showLoading({
						title: '数据获取中'
					});
					this.getFileInfoApp(res.files[0], res.files[0].name)
				})
			},
			getFileInfoApp(path, name) {
				this.apkshow = false
				let that = this
				this.getApkInfo(path, (res) => {
					this.apktemp = res
					this.apktemp.up = this.up
					this.linkshow = true
					uni.hideLoading();
					this.message("获取成功")
				})
				uni.hideLoading();
			},
			uploadApkLink() {
				var that = this
				if (this.apktemp.url == null) {
					this.message('链接不可为空', 'error')
					return
				}
				this.uploadFile(this.apktemp.icon, function(res) {
					that.apktemp.icon = res
					that.apktemp.otherlink = true
					that.apktemp['user_id'] = that.user_id
					that.apktemp['time'] = new Date()
					db.collection("item").add(that.apktemp).then(async res => {
						that.linkshow = false
						that.apktemp = {}
						const itemData = await db.collection("item")
							.where({
								_id: res.result.id
							}).field(that.field).get({
								getOne: true
							})
						that.$refs.udb.dataList.unshift(itemData.result
							.data);
					})
				})
			},
			selectapk() {
				this.apkshow = false
				const plugin = uni.requireNativePlugin('GuoWei-SelectFileModule')
				plugin.chooseFile({
					count: 1,
					extension: ['apk', 'ipa']
				}, res => {
					if (res.code == 1) {
						return
					}
					if (res.files[0].size >= 1024 * 1024 * 100) {
						this.message("文件不得超过100MB", "error")
						return
					}
					this.progressShow = true
					this.progressLoading = true
					setTimeout(() => {
						this.uploadFileLanzou(res.files[0])
					}, 500)
				})
			},
			uploadFileLanzou(file) {
				let that = this
				let form = {}
				if (file.suffix == ".apk") {
					this.getApkInfo(file, (res) => {
						form = res
						form.up = this.up
						form.user_id = store.state.userInfo._id
						form.time = new Date()
						that.uploadFile(res.icon, function(upRes) {
							form.icon = upRes
							that.uploadFileToLanzou(file.path, (upLanRes) => {
								let downInfo = JSON.parse(upLanRes.data)
								let pwdInfo = JSON.parse(upLanRes.password)
								let lanzouUrl =
									`${downInfo.text[0].is_newd}/${downInfo.text[0].f_id}?pwd=${pwdInfo.info.pwd}`
								form.url = lanzouUrl
								db.collection("item").add(form).then(async dbRes => {
									that.progressShow = false
									that.progressLoading = false
									const itemData = await db.collection("item")
										.where({
											_id: dbRes.result.id
										}).field(that.field).get({
											getOne: true
										})
									that.$refs.udb.dataList.unshift(itemData.result
										.data);
									that.message("上传成功")
								})
							})
						})
					})
				} else {
					form = {
						size: file.size,
						weight: 3,
						title: file.name,
						type: 'other',
						icon: this.getIcon(file.suffix),
						openup: 'moren',
						up: this.up,
						user_id: store.state.userInfo._id,
						time: new Date()
					}
					this.uploadFileToLanzou(file.path, (upLanRes) => {
						let downInfo = JSON.parse(upLanRes.data)
						let pwdInfo = JSON.parse(upLanRes.password)
						let lanzouUrl =
							`${downInfo.text[0].is_newd}/${downInfo.text[0].f_id}?pwd=${pwdInfo.info.pwd}`
						form.url = lanzouUrl
						db.collection("item").add(form).then(async (dbRes) => {
							that.progressShow = false
							that.progressLoading = false
							const itemData = await db.collection("item")
								.where({
									_id: dbRes.result.id
								}).field(that.field).get({
									getOne: true
								})
							that.$refs.udb.dataList.unshift(itemData.result
								.data);
							that.message("上传成功")
							uni.hideLoading()
						})
					})
				}
			},
			getIcon(suffix) {
				const filetypeImages = {
					'.zip': "../../static/filetype/yasuowenjian-zip_rar_7z.png",
					'.rar': "../../static/filetype/yasuowenjian-zip_rar_7z.png",
					'.jar': "../../static/filetype/yasuowenjian-zip_rar_7z.png",
					'.7z': "../../static/filetype/yasuowenjian-zip_rar_7z.png",
					'.txt': "../../static/filetype/wenbenwendang-txt.png",
					'.flac': "../../static/filetype/yinle-music.png",
					'.mp3': "../../static/filetype/yinle-music.png",
					'.docx': "../../static/filetype/wendang-docx_doc.png",
					'.doc': "../../static/filetype/wendang-docx_doc.png",
					'.pptx': "../../static/filetype/yanshiwendang-ppt_pptx.png",
					'.xlsx': "../../static/filetype/biaoge-xlxs_xls.png",
					'.pdf': "../../static/filetype/pdf.png",
					'.exe': "../../static/filetype/exe.png",
					'.lua': "../../static/filetype/lua.png"
				};

				return filetypeImages[suffix];
			},
			setswitch(e) {
				this.addset.password_mode = e
			},
			setfileinfo() {
				this.setshow = false
				this.addfileshow = true
				this.fileinfo.title = "修改资料";
				this.fileinfo.button = '修改';
				this.addset = {
					title: this.item_temp.title,
					content: this.item_temp.content,
					password_mode: this.item_temp.password_mode,
					password: this.item_temp.password,
				}
			},
			async add_file() {
				if (this.addset.title == '' || this.addset.title == null) {
					this.message('标题不完整', 'error')
					return false
				}
				if (this.addset.password_mode) {
					if (this.addset.password == null || this.addset.password.length == 0) {
						this.message('密码为空', 'error')
						return false
					}
				}
				this.addset['time'] = new Date()
				this.addset['user_id'] = this.user_id
				this.addset['weight'] = 1
				this.addset['openup'] = "file_jingdian"
				const addData = await db.collection("item").add(this.addset)
				const itemData = await db.collection("item").where({
					_id: addData.result.id
				}).field(this.field).get({
					getOne: true
				})
				this.$refs.udb.dataList.unshift(itemData.result.data);
				this.addfileshow = false
				this.message('创建成功')
			},
			set_file() {
				if (this.addset.password == null && this.addset.password_mode) {
					this.message('密码为空', 'error')
					return null
				}
				this.$refs.udb.update(this.item_temp._id, this.addset, {
					needLoading: false,
					toastTitle: '修改成功',
					success: (res) => {
						this.$refs.udb.dataList[this.index_temp].title = this.addset.title
						this.$refs.udb.dataList[this.index_temp].content = this.addset.content
						this.$refs.udb.dataList[this.index_temp].password_mode = this.addset
							.password_mode
						this.$refs.udb.dataList[this.index_temp].password = this.addset
							.password
						this.addfileshow = false
					}
				})
			},
			filebtn() {
				if (this.fileinfo.button == '创建') {
					this.add_file()
				} else {
					this.set_file()
				}
			},
			async fabclick(i) {
				var that = this
				this.upshow = false
				if (i == 0) {
					this.fileinfo.title = '创建合集'
					this.fileinfo.button = '创建'
					this.addset = {
						title: null,
						content: "",
						password_mode: false,
						password: null,
						type: 'file',
						up: this.up
					}
					this.addfileshow = true
				} else if (i == 1) {
					this.setshow = false
					this.apkshow = true
				} else if (i == 2) {
					this.upshow = false
					if (store.state.userInfo.vip < new Date().getTime()) {
						this.message("该功能为会员专属", "error")
						this.goPage("pay")
					} else {
						this.uploadimg()
					}
				} else if (i == 3) {
					this.goPage('document', '?up=' + this.up)
				} else if (i == 4) {
					this.appOther()
				}
			},
			async upload(path, file, index) {
				let that = this
				return new Promise(async (resolve) => {
					this.progresslist.push({
						name: `第${Number(index)+1}个文件`,
						progress: 0,
						success: false
					})
					let suffix = path.substring(path.lastIndexOf('.') + 1);
					const uniCloudStorageExtCo = uniCloud.importObject("ext-storage-co");
					const uploadFileOptionsRes = await uniCloudStorageExtCo.getUploadFileOptions({
						cloudPath: `image/${Date.now()}${path.split('/').pop()}.${suffix}`,
					});
					const uploadTask = uni.uploadFile({
						...uploadFileOptionsRes.uploadFileOptions,
						filePath: path,
						success: async () => {
							const res = {
								cloudPath: uploadFileOptionsRes.cloudPath,
								fileID: uploadFileOptionsRes.fileID,
								fileURL: uploadFileOptionsRes
									.fileURL,
							};
							await db.collection("imgdatabase").add({
								url: res.fileURL
							})
							let data = {
								size: file.size,
								up: that.up,
								url: res.fileURL,
								title: path.split('/').pop(),
								openup: "moren",
								weight: 5,
								type: "img",
								time: new Date(),
								user_id: store.state.userInfo._id
							}
							db.collection("item").add(data).then(async (res) => {
								that.message(`第${Number(index)+1}个上传成功`)
								const itemData = await db.collection("item")
									.where({
										_id: res.result.id
									}).field(that.field).get({
										getOne: true
									})
								resolve(itemData.result.data);
								that.$set(that.progresslist, index, {
									name: `第${Number(index)+1}个文件`,
									progress: 100,
									success: true
								})
							})
						}
					});
					uploadTask.onProgressUpdate((res) => {
						that.$set(that.progresslist, index, {
							name: `第${Number(index)+1}个文件`,
							progress: res.progress,
							success: false
						})
					});
				});
			},
			appOther() {
				const plugin = uni.requireNativePlugin('GuoWei-SelectFileModule')
				plugin.chooseFile({
					count: 1,
					extension: this.othersuffix
				}, res => {
					if (res.code == 1) {
						return
					}
					if (res.files[0].size >= 1024 * 1024 * 100) {
						this.message("文件不得超过100MB", "error")
						return
					}
					this.progressShow = true
					this.progressLoading = true
					setTimeout(() => {
						this.uploadFileLanzou(res.files[0])
					}, 500)
				})
			},
			uploadimg() {
				var that = this
				uni.chooseImage({
					count: 9,
					sourceType: ['album'],
					success: function(seleimg) {
						Promise.all(seleimg.tempFilePaths.map((item, i) => {
							return that.upload(item, seleimg.tempFiles[i], i)
						})).then(res => {
							that.closeProgress()
							res.map(item => {
								that.$refs.udb.dataList.unshift(item)
							})
						})
					}
				})
			},
			shareapp(info) {
				if (this.client == 'web') {
					this.copy("http://x2.ink/pages/share/share?id=" + info._id, "链接复制成功")
					return
				}
				var icon = this.geticon(info.type, info.icon)
				if (icon.indexOf("../../") >= 0) {
					icon = icon.replace("../../", "http://x2.ink/")
				}
				uni.share({
					provider: "qq",
					type: 0,
					title: info.title,
					href: "https://x2.ink/pages/share/share?id=" + info._id,
					imageUrl: icon,
					summary: "我在小二云盘发现了一款超级好玩的文件！赶紧来看看吧！"
				});
			},
			dele() {
				if (this.item_temp._id == null) {
					return null
				}
				this.setshow = false
				if (this.item_temp.type == 'file') {
					this.delefile()
				} else {
					this.deleitem()
				}
			},
			deleitem() {
				var that = this
				uni.showModal({
					title: '提示',
					content: '你正在执行删除操作，操作不可逆！',
					success: function(res) {
						if (res.confirm) {
							uniCloud.callFunction({
								name: 'deleitem',
								data: {
									_id: that.item_temp._id,
									url: that.item_temp.url
								},
								success(res) {
									that.message('删除成功')
									that.$refs.udb.remove(that.item_temp._id, {
										needConfirm: false,
										needLoading: false
									})
								}
							})
						}
					}
				});
			},
			delefile() {
				if (this.item_temp._id == null) {
					return null
				}
				var that = this
				uni.showModal({
					title: '提示',
					content: '你正在执行删除操作，操作不可逆，包括集合内文件也会被删除！！',
					success: function(res) {
						if (res.confirm) {
							uni.showLoading({
								title: '正在删除中'
							});
							uniCloud.callFunction({
								name: 'delefile',
								data: {
									id: that.item_temp._id
								},
								success(res) {
									that.$refs.udb.remove(that.item_temp._id, {
										needConfirm: false,
										needLoading: false
									})
									uni.hideLoading()
								}
							})
						}
					}
				});
			},
			downitem() {
				this.setshow = false
				if (this.item_temp._id == null) {
					return null
				}
				this.$refs.udb.update(this.item_temp._id, {
					top: 0,
					last_time: null
				}, {
					needLoading: false,
					toastTitle: '取消成功',
					success: () => {
						this.item_temp.top = 0
						this.item_temp.last_time = null
					}
				})
			},
			topitem() {
				this.setshow = false
				if (this.item_temp._id == null) {
					return null
				}
				this.$refs.udb.update(this.item_temp._id, {
					top: 1,
					last_time: new Date()
				}, {
					needLoading: false,
					toastTitle: '置顶成功',
					success: () => {
						this.item_temp.top = 1
						this.item_temp.last_time = new Date()
					}
				})
			},
			async passitem() {
				if (this.classifyTemp == "未选择") {
					this.message('请选择分类', 'error')
					return
				}
				if (store.state.userInfo.identity == "认证") {
					const res = await db.collection("item").where({
						_id: this.item_temp._id
					}).update({
						status: false,
						pass_time: new Date(),
						money: Number(this.item_temp.money),
						pass: true,
						classify_id: this.item_temp.classify_id
					})
					this.message('上架成功')
				} else {
					const res = await db.collection("item").where({
						_id: this.item_temp._id
					}).update({
						status: true,
						pass_time: new Date(),
						money: Number(this.item_temp.money),
						classify_id: this.item_temp.classify_id
					})
					this.message('申请成功')
				}
				this.classifyTemp = "未选择"
				this.fbsqshow = false
			},
			async qxpassitem() {
				const res = await db.collection("item").where({
					_id: this.item_temp._id
				}).update({
					pass: false,
					status: false,
					pass_time: new Date(),
					money: this.item_temp.money
				})
				this.message('撤回成功')
				this.fbsqshow = false
			},
			save() {
				this.$refs.uqrcode.save({
					success: () => {
						this.message('保存成功')
					}
				});
			},
			setname() {
				var that = this
				this.setnameshow = false
				if (this.item_temp._id == null || this.item_temp._id == "" || this.rename.length == 0) {
					this.message("内容为空", 'error')
					return null
				}
				this.$refs.udb.update(this.item_temp._id, {
					title: this.rename
				}, {
					toastTitle: "修改成功",
					success() {
						that.item_temp.title = that.rename
						that.rename = ""
					}
				})
			},
			async getlink(id, title) {
				const res = await uniCloud.callFunction({
					name: 'addlink',
					data: {
						data: ase.encrypt(JSON.stringify({
							item_id: id,
							title: title
						}), 'yclycl1314520520', '9740022097400220')
					}
				})
				this.link = res.result.to
			},
			setinfo(item, index) {
				item.sizes = item.size == null ? '' : this.gsbytes(item.size)
				this.getlink(item._id, item.title)
				item.time = uni.$u.timeFormat(item.time, 'yyyy-mm-dd hh:MM');
				this.item_temp = item
				this.index_temp = index
				this.setshow = true
			},
			to(title, up) {
				this.path.push({
					name: title,
					to: up
				})
				this.up = up
			},
			listclick(item, index) {
				if (item.type == 'file') {
					this.to(item.title, item._id)
				} else if (item.type == 'img') {
					this.openImg([item.url], index)
				} else if (item.type == 'apk' || item.type == 'ipa') {
					this.goPage('apk', '?type=apk&id=' + item._id)
				} else if (item.type == 'video') {
					this.goPage('share', '?id=' + item._id + '&client=app&user_id=' + this
						.user_id)
				} else if (item.type == 'document') {
					this.goPage('document', '?id=' + item._id)
				} else if (item.type == 'other') {
					let arr = [
						"../../static/filetype/yasuowenjian-zip_rar_7z.png",
						"../../static/filetype/wenbenwendang-txt.png",
						"../../static/filetype/yinle-music.png",
						"../../static/filetype/wendang-docx_doc.png",
						"../../static/filetype/yanshiwendang-ppt_pptx.png",
						"../../static/filetype/biaoge-xlxs_xls.png",
						"../../static/filetype/pdf.png",
						"../../static/filetype/exe.png",
						"../../static/filetype/lua.png"
					]
					if (!arr.includes(item.icon)) {
						this.goPage('apk', '?type=other&id=' + item._id)
						return
					}
					if (item.icon.indexOf('exe.png') > 0 || item.icon.indexOf(
							'yasuowenjian-zip_rar_7z.png') > 0) {
						this.goPage('apk', '?type=other&id=' + item._id)
					} else {
						this.setinfo(item, index)
					}
				} else {
					this.setinfo(item, index)
				}
			},
			back(e, index) {
				if (e == this.up) {
					return false
				}
				this.path.splice(index + 1)
				this.up = e
			},
			sousuo(e) {
				if (e == null || e == "") {
					return false
				}
				this.itemwhere = `user_id==$cloudEnv_uid&&/${e}/.test(title)`
				this.$nextTick(() => {
					this.$refs.udb.loadData({
						clear: true
					})
				})
			},
			loadlist(data) {
				uni.stopPullDownRefresh()
			},
			ctabs(e) {
				this.tabcurrent = e.weight
				this.itemwhere =
					`user_id==$cloudEnv_uid&&weight==${e.weight}&&up=='${this.up}'`
				if (this.search != null && this.search != "") {
					this.itemwhere =
						`user_id==$cloudEnv_uid&&/${this.search}/.test(title)&&weight==${e.weight}`
				}
				if (e.weight == null) {
					if (this.search != null && this.search != "") {
						this.itemwhere =
							`user_id==$cloudEnv_uid&&/${this.search}/.test(title)`
					} else {
						this.itemwhere = `user_id==$cloudEnv_uid&&up=='${this.up}'`
					}
				}
				if (e.name == "全部") {
					this.itemwhere = `user_id==$cloudEnv_uid&&up=='${this.up}'`
				}
				this.$nextTick(() => {
					this.$refs.udb.loadData({
						clear: true
					})
				})
			}
		},
		onBackPress() {
			if (this.up != "/") {
				this.up = this.path[this.path.length - 2].to
				this.path.splice(this.path.length - 1, 1)
				return true
			}
		}
	}
</script>
<style scoped lang="scss">
	.u-search {
		background-color: white;
		padding: 0 10px;
	}

	.navbar>view {
		display: flex;
		align-items: center;
	}

	.file-list {
		height: calc(100vh - 178px - var(--status-bar-height) / 2);
		background-color: white;
		border-radius: 15px 15px 0 0;
		padding-top: 5px;
	}

	.save-qrcode {
		text-align: center;
		font-size: 14px;
		color: #909399;
	}

	.release-community {
		padding: 10px;
		border-radius: 10px 10px 0 0;
		background-color: white;
	}

	.release-community .classify {
		display: flex;
		justify-content: space-between;
		align-items: center;
		height: 40px;
	}

	.file-info {
		padding: 10px;
		border-radius: 10px 10px 0 0;
		background-color: white;
	}

	.file-operate {
		padding: 10px;
		border-radius: 10px 10px 0 0;
		background-color: white;
	}

	.u-grid-item {
		margin-top: 5px;
	}

	.u-grid-item>view {
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.u-grid-item>view>p {
		color: #606266;
		margin-left: 5px;
		font-size: 14px;
	}

	.create-files {
		padding: 15px;
		width: 250px;
	}

	.create-files .password {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-top: 10px;
	}

	.create-files .password>view {
		font-size: 14px;
		display: flex;
		align-items: center;
	}

	.apk-type {
		padding: 10px;
		border-radius: 10px 10px 0 0;
		background-color: white;
	}

	.apk-type .type {
		display: flex;
		justify-content: space-around;
	}

	.apk-type .type>view {
		text-align: center;
	}

	.apk-type .type>view>p {
		color: #85bcff;
	}

	.upload-file {
		padding: 10px;
		border-radius: 10px 10px 0 0;
		background-color: white;
	}

	.upload-file .tip {
		background-color: #fff6e4;
		border-radius: 5px;
		padding: 5px;
		margin: 10px;
		font-size: 13px;
		color: #7b7458;
	}

	.upload-file .wx {
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 14px;
	}

	.upload-file .info {
		background-color: #f1f1f1;
		height: 90px;
		border-radius: 5px;
		display: flex;
		align-items: center;
		padding: 0 10px;
		margin-top: 10px;
	}

	.upload-file .down {
		position: absolute;
		height: 40px;
		right: 30px;
	}
</style>